package com.zbkj.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.service.AgentClientService;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.client.agent.*;
import com.zbkj.common.model.client.digital.DpVoice;
import com.zbkj.common.model.client.workbench.VideoSubtitle;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.dao.client.WeekTaskDao;
import com.zbkj.service.service.*;
import com.zbkj.client.config.SSESessionManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Array;
import java.sql.Date;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 客户端首页控制器
 */
@Slf4j
@RestController
@RequestMapping("api/client/index")
@Api(tags = "客户端首页控制器")
public class IndexController {

    @Autowired
    private AgentClientService agentClientService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private UserLocationService userLocationService;

    @Autowired
    private WeekTaskService weekTaskService;

    @Autowired
    private SpecialHotTopicService specialHotTopicService;

    @Autowired
    private SSESessionManager sseSessionManager;

    @Autowired
    private ContentCreateService contentCreateService;

    @Autowired
    private SystemAdminService systemAdminService;

    @Autowired
    private ThirdHotService thirdHotService;

    @Autowired
    private WeekTaskDao weekTaskDao;

    private final RestTemplate restTemplate = new RestTemplate();

    @ApiOperation(value = "一句话定位")
    @PostMapping(value = "/generateUserLocation", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void generateUserLocation(@RequestBody Map<String, Object> requestBody, 
                                   @RequestParam(required = false) String sessionId,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {

        String message = (String) requestBody.get("desc");
        
        log.info("generateUserLocation开始处理，message: {}, sessionId: {}", message, sessionId);
        
        // 如果没有提供sessionId，尝试从请求头获取
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = request.getHeader("X-Session-ID");
            log.info("从请求头获取sessionId: {}", sessionId);
        }
        
                   // 调用AgentClientService的chatStream方法
           // 使用固定的agentId: 8b44308c-5f29-4490-b7eb-46ca36ead41b
           String agentId = "8b44308c-5f29-4490-b7eb-46ca36ead41b";
           agentClientService.chatStream(agentId, message, sessionId, null, response, null, null, null);
    }


    @ApiOperation(value = "用户定位确认")
    @PostMapping(value = "/userLocationFix")
    public CommonResult<?> userLocationFix(@RequestBody Map<String, Object> requestBody, HttpServletRequest request) {

        String message = (String) requestBody.get("message");
        String desc = (String) requestBody.get("desc");
        //是否是重新定位
//        Integer isFresh = (Integer) requestBody.get("isFresh");
        log.info("收到用户位置分析请求，message: {}", message);

        Integer userId = clientTokenComponent.getLoginUser(request);
        String token = request.getHeader("token");
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();

        //查询同一个租户下的所有的用户
        QueryWrapper<SystemAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .eq("mer_id", merId);

        List<SystemAdmin> userListByMerId = systemAdminService.list(wrapper);

        //是否需要重新定位
        // 异步调用 agentClientService.insertUserLocation 和 agentClientService.insertWeekTask
        CompletableFuture.runAsync(() -> {
            try {
                // insertUserLocation执行完毕后再执行createTopic，保证顺序

                //先生成主账号的定位信息
                UserLocation userLocationTemp = agentClientService.insertUserLocation(desc, message, userId, merId);

                //生成所有子账号的定位信息，不用调用api，直接复制主账号下的
                for(SystemAdmin userLocationInsert : userListByMerId){
                    if (userLocationInsert.getId() != userId){
                        agentClientService.insertSubUserLocation(userLocationTemp.getId(), userLocationInsert.getId());
                    }
                }

                //先生成主账号的榜单
                Map<String, Object> agentUserInfo = agentClientService.getAgentUserInfo(userLocationTemp);
                agentClientService.createTopic(userId, merId, agentUserInfo);

                //创建子账号的专业热榜
                for (SystemAdmin user : userListByMerId){
                    if (user.getId() != userId){
                        agentClientService.createTopic(user.getId(), merId, agentUserInfo);
                    }
                }
            } catch (Exception e) {
                log.error("异步插入用户位置或创建话题失败", e);
            }
        });

        //异步生成周任务
        CompletableFuture.runAsync(() -> {
            try {
                for (SystemAdmin userTask : userListByMerId){
                    agentClientService.insertWeekTask(message, userTask.getId(), merId);
                }
            } catch (Exception e) {
                log.error("异步插入周任务失败", e);
            }
        });

        return CommonResult.success("提交成功");
    }

    /**
     * 获取每日任务列表
     * @param httpRequest
     * @return
     */
    @GetMapping("/getWeekTaskList")
    public CommonResult<List<WeekTask>> getWeekTaskList(HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        Map<String, String> weekDates = agentClientService.getCurrentWeekDates();
        String mondayDate = weekDates.get("monday");
        String sundayDate = weekDates.get("sunday");

        QueryWrapper<WeekTask> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .eq("user_id", userId)
                .ge("day", Date.valueOf(mondayDate))
                .le("day", Date.valueOf(sundayDate))
                .eq("week", "first")
                .orderByAsc("day");

        List<WeekTask> res = weekTaskService.list(wrapper);

        return CommonResult.success(res);
    }

    /**
     * 获取每用户定位信息
     * @param httpRequest
     * @return
     */
    @GetMapping("/getUserlocationDetail")
    public CommonResult<UserLocation> getUserlocationDetail(HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        UserLocation userLocation = userLocationService.lambdaQuery()
                .eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getIsDel, 0)
                .one();

        if (userLocation != null) {
            return CommonResult.success(userLocation);
        } else {
            return CommonResult.failed("未找到对应的用户定位信息");
        }
    }

    /**
     * 获取每用户定位信息
     * @param httpRequest
     * @return
     */
    @GetMapping("/getWeekTaskDetail")
    public CommonResult<WeekTask> getWeekTaskDetail(@RequestParam Integer id, HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        WeekTask weekTask = weekTaskService.getById(id);

        if (weekTask != null) {
            return CommonResult.success(weekTask);
        } else {
            return CommonResult.failed("未找到对应的用户定位信息");
        }
    }

    @ApiOperation(value = "周任务换一批")
    @GetMapping(value = "/changeBatchTask")
    public CommonResult<String> changeBatchTask(HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        String token = httpRequest.getHeader("token");

        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();

        String message = "";


        UserLocation byUserId = userLocationService.getByUserId(userId);
        if (byUserId != null) {
            message = byUserId.getLocationResult();
        }


        if (message == null ||  message.isEmpty()) {
            return CommonResult.failed("请等待用户定位完成");
        }

        final String finalMessage = message;
        CompletableFuture.runAsync(() -> {
            try {
                agentClientService.insertWeekTask(finalMessage, userId, merId);
            } catch (Exception e) {
                log.error("异步插入周任务失败", e);
            }
        });

        return CommonResult.success("提交成功");
    }

    @ApiOperation(value = "文案创作")
    @PostMapping(value = "/contentCreate", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void contentCreate(@RequestBody Map<String, Object> requestBody, 
                             HttpServletRequest httpRequest, 
                             HttpServletResponse response) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        String token = httpRequest.getHeader("token");
        ClientLoginResponse userInfo1 = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo1 != null ? userInfo1.getMerId() : null;

        String message = (String) requestBody.get("message");
        String sessionId = (String) requestBody.get("sessionId");
        Integer weekTaskId = (Integer) requestBody.get("weekTaskId");
        Integer hotTopicId = (Integer) requestBody.get("hotTopicId");
        Integer douyinId = (Integer) requestBody.get("douyinId"); //如果是抖音热榜创作

        String recommendTag = (String) requestBody.get("recommendTag");//推荐标签
        String desc = (String) requestBody.get("desc");//描述

        String source = "other";

        Map<String, Object> userInfoRequestJson = new HashMap<>();

        UserLocation userLocation = userLocationService.getByUserId(userId);
        //用户定位信息可以还未完成，即做了文案创作
        if (userLocation != null) {
            userInfoRequestJson = agentClientService.getAgentUserInfo(userLocation);
        }

        log.info("收到文案创作请求，message: {}, sessionId: {}", message, sessionId);


        //拼接message信息，文案创作可能是每日任务进来的(weekTaskId)，可能是专业热榜进来的(hotTopicId)，也可能是抖音热榜来的
        if(weekTaskId != null){
            WeekTask weekTask = weekTaskService.getById(weekTaskId);
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("content_type", weekTask.getContentType());
            hashMap.put("task_description", weekTask.getTaskDescription());
            hashMap.put("recommended_topic", weekTask.getRecommendedTopic());
            hashMap.put("target_audience", weekTask.getTargetAudience());
            hashMap.put("task_purpose", weekTask.getTaskPurpose());
            hashMap.put("content_attribute", weekTask.getContentAttribute());
            hashMap.put("strategy_focus", weekTask.getStrategyFocus());

            message = JSON.toJSONString(hashMap);
            source = "week_task";
        }

        if(douyinId != null){
            ThirdHot thirdHot = thirdHotService.getById(douyinId);
            HashMap<Object, Object> hashMap = new HashMap<>();

            hashMap.put("title", thirdHot.getTitle());
            hashMap.put("description", thirdHot.getDescription());

            message = JSON.toJSONString(hashMap);
            source = "douyin";
        }


        //热榜的message信息
        if (hotTopicId != null) {
            SpecialHotTopic specialHotTopic = specialHotTopicService.getById(hotTopicId);
            HashMap<Object, Object> hashMap = new HashMap<>();

            hashMap.put("category", specialHotTopic.getCategory());
            hashMap.put("target_analysis", specialHotTopic.getTargetAnalysis());
            hashMap.put("title", specialHotTopic.getTitle());
            hashMap.put("description", specialHotTopic.getDescription());
            hashMap.put("purpose", specialHotTopic.getPurpose());

            message = JSON.toJSONString(hashMap);

            source = "hot_topic";
        }

        log.info("message信息为：{}", message);

        Map<String, Object> params = new HashMap<>();
        params.put("message", message);
        params.put("userId", userId);
        params.put("merId", merId);
        params.put("weekTaskId", weekTaskId);
        params.put("hotTopicId", hotTopicId);
        params.put("thirdHotId", douyinId);
        params.put("recommendTag", recommendTag);
        params.put("userInfo", userInfoRequestJson);
        params.put("desc", desc);
        params.put("source", source);

        String agentId = "13abe95f-2b89-4333-a9de-69148fff5bf3";
        agentClientService.chatStream(agentId, message,sessionId, userInfoRequestJson,response, "insertContentCreate", params, null);
    }

    /**
     * 获取文案创作详情
     * @param weekTaskId 任务ID
     * @param id 逻辑id
     * @return
     */
    @GetMapping("/getContentCreateDetail")
    public CommonResult<?> getContentCreateDetail(@RequestParam (required = false) String weekTaskId, @RequestParam (required = false) Integer id) {

        ContentCreate contentCreate = null;
        if (weekTaskId != null && !weekTaskId.isEmpty()) {
            contentCreate = contentCreateService.lambdaQuery()
                    .eq(ContentCreate::getWeekTaskId, weekTaskId)
                    .orderByDesc(ContentCreate::getCreateTime)
                    .last(" limit 1")
                    .one();

        }else if (id != null) {
            contentCreate = contentCreateService.getById(id);
        }

        return CommonResult.success(contentCreate);
    }

    /**
     * 获取文案创作列表
     * @param httpRequest
     * @return
     */
    @GetMapping("/getContentCreateList")
    public CommonResult<IPage<ContentCreate>> getContentCreateList(@RequestParam(value = "page", defaultValue = "1") int page,
                                                                  @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                                                  HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        Page<ContentCreate> pageParam = new Page<>(page, pageSize);
        QueryWrapper<ContentCreate> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .eq("user_id", userId)
                .in("source", Arrays.asList("hot_topic", "other"))
                .orderByDesc("create_time");

        IPage<ContentCreate> res = contentCreateService.page(pageParam, wrapper);


        return CommonResult.success(res);
    }

    @ApiOperation(value = "魔法笔")
    @PostMapping(value = "/magicPen", produces = MediaType.TEXT_PLAIN_VALUE)
    public void magicPen(@RequestBody Map<String, Object> requestBody,
                                         HttpServletRequest httpRequest,
                                         HttpServletResponse response) {

        // 18148f52-3e06-4349-a9d1-bbc774ed3a53
        String message = (String) requestBody.get("desc");
        String sessionId = (String) requestBody.get("sessionId");

        //加上用户信息
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        String token = httpRequest.getHeader("token");
        ClientLoginResponse userInfo1 = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo1 != null ? userInfo1.getMerId() : null;

        UserLocation userLocation = userLocationService.getByUserId(userId);

        // 2. 拼接user_info参数
        Map<String, Object> userInfoRequestJson = new HashMap<>();

        if (userLocation != null) {
            userInfoRequestJson = agentClientService.getAgentUserInfo(userLocation);
        }

        log.info("魔法笔开始处理，message: {}, sessionId: {}", message, sessionId);

        // 如果没有提供sessionId，尝试从请求头获取
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = httpRequest.getHeader("X-Session-ID");
            log.info("从请求头获取sessionId: {}", sessionId);
        }

        // 调用AgentClientService的chatStream方法
        // 使用固定的agentId: 8b44308c-5f29-4490-b7eb-46ca36ead41b
        String agentId = "18148f52-3e06-4349-a9d1-bbc774ed3a53";

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("merId", merId);

        agentClientService.chatStream(agentId, message, sessionId, userInfoRequestJson, response, null, params,null);
    }

    @ApiOperation(value = "用户定位确认")
    @GetMapping(value = "/test")
    public CommonResult<?> test(HttpServletRequest request) {

        Integer userId = clientTokenComponent.getLoginUser(request);
        String token = request.getHeader("token");
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();

        UserLocation byUserId = userLocationService.getByUserId(userId);

        agentClientService.insertWeekTask(byUserId.getLocationResult(), userId, merId);

//        agentClientService.createTopic(userId, merId);

        return CommonResult.success("提交成功");
    }

} 